package org.keyyond.ms.gateway.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MsCustomerRequestWrapper extends HttpServletRequestWrapper {

	private final byte[] body;

	public MsCustomerRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		// body = StreamUtil.readBytes(request.getReader(), JoddDefault.encoding); 
		// 因为http协议默认传输的编码就是iso-8859-1,如果使用utf-8转码乱码的话，可以尝试使用iso-8859-1
		InputStream stream = request.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[request.getContentLength()];
        int n=0;
        while ( (n=stream.read(buffer)) !=-1) {
            out.write(buffer,0,n);
        }
        body = out.toByteArray();
//		body = StreamUtil.readBytes(request.getReader(), Constant.ENCODING_UTF_8);
    }

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);
		return new ServletInputStream() {

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener listener) {
				// TODO Auto-generated method stub

			}

			@Override
			public int read() throws IOException {
				// TODO Auto-generated method stub
				return bais.read();
			}

		};
	}

}
